package com.starrin.tennisfinder.scheduler;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.starrin.tennisfinder.extractors.ExtractTennisStadion;
import com.starrin.tennisfinder.model.VenueAvailabilityDataHolder;
import com.starrin.tennisfinder.system.Cache;
import com.starrin.tennisfinder.util.DateUtil;
import com.starrin.tennisfinder.util.WebUtil;
import org.apache.log4j.Logger;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by larsstarrin on 09/02/14.
 */
public class RefreshTennisStadion implements Runnable {
    private Cache cache = Cache.getInstance();
    private static final Logger logger = Logger.getLogger(RefreshTennisStadion.class);
    private String venueKey;
    private static final int FORESIGHT_DAYS = 15;
    private Map<String, VenueAvailabilityDataHolder> newData = new HashMap<>();


    public RefreshTennisStadion(String venueKey) {
        this.venueKey = venueKey;
    }

    public void run() {
        logger.info("Start refreshing availability data for " + venueKey);
        try {
            long start = System.currentTimeMillis();
            refresh();
            //Put temp data into cache
            for (Map.Entry<String, VenueAvailabilityDataHolder> entry : newData.entrySet()) {
                cache.putEntry(entry.getKey(), venueKey, entry.getValue());
            }
            logger.info("Finished refreshing availability data for " + venueKey + " in " + (System.currentTimeMillis() - start) / 1000 + " seconds");

        } catch (Exception e) {
            logger.error("Error fetching data", e);
        }

    }

    private void refresh() throws Exception {
        WebClient webClient = new WebClient();
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setJavaScriptEnabled(false);

        //Login
        WebRequest loginRequest = new WebRequest(new URL("http://extweb20.dlsoftware.com/index.php?func=do_login&tak=0.88582700+1391917462"), HttpMethod.POST);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new NameValuePair("txt_login", "13926"));
        params.add(new NameValuePair("psw_password", "13926"));
        params.add(new NameValuePair("btn_login", "Logga in"));
        loginRequest.setRequestParameters(params);
        webClient.getPage(loginRequest);
        String reduceResponseSearchPoint = "07:00 - 08:00";

        for (int i = 0; i < FORESIGHT_DAYS; i++) {
            Calendar cal = new GregorianCalendar();
            cal.add(Calendar.DAY_OF_MONTH, i);
            SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
            String dateString = df.format(cal.getTime());
            String urlTemplate = "http://extweb20.dlsoftware.com/index.php?cdate=%s&pageId=1&func=MOD_RC_V2&tac=";
            String url = String.format(urlTemplate, dateString);
            String response = webClient.getPage(url).getWebResponse().getContentAsString();

            try {
                response = WebUtil.getReducedResponse(response, reduceResponseSearchPoint);
                if (response != null) {
                    VenueAvailabilityDataHolder dataHolder = new ExtractTennisStadion().extractVenueAvailability(response, url);
                    newData.put(new DateUtil().getAsString(cal.getTime()), dataHolder);
                }
            } catch (StringIndexOutOfBoundsException e) {
                logger.error("Could not get reduced response for " + venueKey + "date=" + dateString + " serchpoint= " + reduceResponseSearchPoint + " cause: " + e.getLocalizedMessage());
            }

        }
    }
}
